package com.totowoo.shirodemo.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;

import com.totowoo.shirodemo.util.AesEncryptUtil;

/**
 * 自定义的密码验证器
 * @author chz
 *
 */

public class CredentialsMatcher extends SimpleCredentialsMatcher {

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String passwordStr = new String(usernamePasswordToken.getPassword());
		
		Session session = SecurityUtils.getSubject().getSession();
		String key = (String) session.getAttribute("temporaryKey");
		
		try {
			passwordStr = AesEncryptUtil.desEncrypt(passwordStr, key, key);
			session.removeAttribute("temporaryKey");			
		} catch (Exception e) {
			e.printStackTrace();
			throw new IncorrectCredentialsException("怀疑受到重放攻击！");			
		}
		
		Object formPassword = new SimpleHash("MD5", passwordStr, usernamePasswordToken.getUsername(), 1024).toString();
		Object storedPassword = info.getCredentials();
		
		return formPassword.equals(storedPassword);
	}
	
	

}
